package com.simon.hse.activity.education;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.activity.SignActivity;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.MyTrainInput;
import com.simon.hse.http.entity.MyTrainOutput;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

/**
 * 我的培训
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_my_train)
public class MyTrainActivity extends BaseActivity {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.et_my_train_name)
    EditText mEt_my_train_name;

    @ViewInject(R.id.smartrefresh)
    SmartRefreshLayout mSmartRefresh;

    @ViewInject(R.id.recyclerview)
    RecyclerView mRecyclerView;

    private int currentPage = 1, totalPage = 1;
    private CommonEmptyAdapter mCommonEmptyAdapter;
    private List<MyTrainOutput.DataBean.PageDataBean> mDataBeanList = new ArrayList<>();// 我的培训列表

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTv_common_title.setText("我的培训");

        initRecyclerView();
        initData();
    }

    @Event(value = {R.id.iv_common_left})
    private void back(View view) {
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
        }
    }

    private void initRecyclerView() {
        mEt_my_train_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                initData();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mSmartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (currentPage * 10 < totalPage) {
                    currentPage++;
                    initData();
                } else {
                    mSmartRefresh.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                mDataBeanList.clear();
                initData();
            }
        });

        LinearLayoutManager llm = new LinearLayoutManager(MyTrainActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        mCommonEmptyAdapter = new CommonEmptyAdapter(MyTrainActivity.this, R.layout.layout_item_train, mDataBeanList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<MyTrainOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, final MyTrainOutput.DataBean.PageDataBean dataBean) {
                TextView tv_my_train_name = holder.getView(R.id.tv_my_train_name);
                TextView tv_my_train_score = holder.getView(R.id.tv_my_train_score);
                TextView tv_my_train_type = holder.getView(R.id.tv_my_train_type);
                TextView tv_my_train_state = holder.getView(R.id.tv_my_train_state);
                TextView tv_my_train_content = holder.getView(R.id.tv_my_train_content);
                TextView tv_my_train_purpose = holder.getView(R.id.tv_my_train_purpose);
                TextView tv_my_train_place = holder.getView(R.id.tv_my_train_place);
                TextView tv_my_train_time = holder.getView(R.id.tv_my_train_time);
                TextView tv_my_train_study = holder.getView(R.id.tv_my_train_study);
                TextView tv_my_train_input = holder.getView(R.id.tv_my_train_input);
                TextView tv_peixun_fankui_input = holder.getView(R.id.tv_peixun_fankui_input);
                TextView tv_yuangong_qianzi_input = holder.getView(R.id.tv_yuangong_qianzi_input);

                tv_my_train_name.setText(dataBean.getMark01());

                if (dataBean.getMark07().equals("已通知")) {
                    tv_my_train_score.setText("未开始");
                    tv_my_train_score.setBackgroundResource(R.drawable.rect_dark_gray_corner_bottom_5);
                } else {
                    tv_my_train_score.setText(dataBean.getScore() + "");
                    if (dataBean.getMark04().equals("未通过")) {
                        tv_my_train_score.setBackgroundResource(R.drawable.rect_red_corner_bottom_5);
                    } else {
                        tv_my_train_score.setBackgroundResource(R.drawable.rect_green_corner_bottom_5);
                    }
                }
                tv_my_train_type.setText("培训类型：" + dataBean.getMark02());
                tv_my_train_state.setText("培训状态：" + dataBean.getMark07());
                tv_my_train_content.setText("培训内容：" + dataBean.getTrainingcontent());
                tv_my_train_purpose.setText("培训目标：" + dataBean.getTarget());

                tv_my_train_place.setText(dataBean.getTrainingvenues());
                String time = dataBean.getTrainingBeginTime();
                if (!TextUtils.isEmpty(time) && time.length() > 16) {
                    time = time.substring(0, 16);
                }
                tv_my_train_time.setText(time);

                tv_my_train_study.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(MyTrainActivity.this, LearningContentActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("ID", dataBean.getId());
                        bundle.putBoolean("SHOW_TIME", true);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });

                tv_my_train_input.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(MyTrainActivity.this, TrainInputActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("TYPE", 0);
                        bundle.putString("ID", dataBean.getId());
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                });

                tv_peixun_fankui_input.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(MyTrainActivity.this, FanKuiInputActivity.class);
                        startActivity(intent);
                    }
                });

                tv_yuangong_qianzi_input.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(MyTrainActivity.this, SignActivity.class);
                        startActivity(intent);
                    }
                });

            }
        });

        mCommonEmptyAdapter.setOnItemEmptyClickListener(new CommonEmptyAdapter.OnItemEmptyClickListener() {
            @Override
            public void setOnEmptyClickListener() {
                initData();
            }

            @Override
            public void setOnItemClickListener(View view, int position) {
                Intent intent = new Intent(MyTrainActivity.this, TrainInputActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("TYPE", 1);
                bundle.putString("ID", mDataBeanList.get(position).getId());
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mCommonEmptyAdapter.setHasStableIds(true);
        mRecyclerView.setAdapter(mCommonEmptyAdapter);
    }

    private void initData() {
        MyTrainInput myTrainInput = new MyTrainInput();
        MyTrainInput.ModelBean modelBean = new MyTrainInput.ModelBean();
        String trainName = mEt_my_train_name.getText().toString();
        if (!TextUtils.isEmpty(trainName)) {
            modelBean.setNameoftrainingplan(trainName);
        }
        myTrainInput.setModel(modelBean);
        myTrainInput.setLimit(10);
        myTrainInput.setOffset(10 * (currentPage - 1));

        Call<String> call = HttpManager.getInstance().requestService().MY_TRAIN_LIST(HttpManager.getInstance().requestBody(myTrainInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                MyTrainOutput myTrainOutput = new Gson().fromJson(result, MyTrainOutput.class);
                if (myTrainOutput.getResult().equals("Success")) {
                    totalPage = myTrainOutput.getData().getRowCount();
                    List<MyTrainOutput.DataBean.PageDataBean> dataBeanList = myTrainOutput.getData().getPageData();
                    mDataBeanList.addAll(dataBeanList);
                    mCommonEmptyAdapter.notifyDataSetChanged();

                    mSmartRefresh.finishRefresh();
                    mSmartRefresh.finishLoadMore();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(myTrainOutput.getMessage().toString());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = data.getExtras();

        if (bundle == null)
            return;

        if (requestCode == 1) {
            currentPage = 1;
            mDataBeanList.clear();
            initData();
        }
    }
}
